import Taro from '@tarojs/taro'
import { useSelector } from 'react-redux'
import React, { useEffect, useState, useCallback } from 'react'
import { date } from '@pier88health/p8h-common'
import api from '@API'
import { View, Image } from '@tarojs/components'
import { Analytic_Type } from '@CONSTANTS/analytic'
import {
  convertParamsToString, getPlatform, checkIsAndroid, getPathname, openPage
} from '@UTILS/common'
import Scenes from '@NAVIGATION/scenes'
import { DISPLAY_FREQUENCY_ENUM, CLICK_HOME_BUTTON } from '@CONSTANTS/app'
import Images from '@ASSET/Images'
import { STORAGE_KEY } from '@CONSTANTS/common'
import DBConfig from '@CONFIG/DBConfig'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import './index.scss'

const { isWeb } = getPlatform()
const IOS_H5_STYLE = isWeb && !checkIsAndroid() ? { position: 'absolute' } : {}

export default function HomePopUp({ showLogin }) {
  const language = 'zh'
  const user = useSelector(state => state.profile.user)
  const [visible, setVisible] = useState(false)
  const [data, setData] = useState(null)
  const fetchPopupEvent = useCallback(async () => {
    try {
      const result = await api.getPopupEventByUserId({ code: 'HomePopup' })
      if (!result) {
        Taro.removeStorageSync(STORAGE_KEY.home_pop_up_key)
        return
      }
      const { p8Id, DisplayFrequency, ModifiedDate } = result
      const lastResult = Taro.getStorageSync(STORAGE_KEY.home_pop_up_key)
      const curDate = date.dateFormat(Date.now(), 'yyyy-MM-dd')
      const isSameDay = curDate === lastResult?.ShowDate
      const isSame = lastResult?.p8Id === p8Id && lastResult?.ModifiedDate === ModifiedDate
      if (DisplayFrequency === DISPLAY_FREQUENCY_ENUM.Once && (!isSame || isSame && !isSameDay)) {
        Taro.setStorageSync(STORAGE_KEY.home_pop_up_key, Object.assign(result, { ShowDate: curDate }))
      }
      if (DisplayFrequency === DISPLAY_FREQUENCY_ENUM.Once && isSame && isSameDay) return
      setData(result)
      setVisible(true)
    } catch (e) {
      Taro.showToast({ title: e.message || e, icon: 'none' })
    }
  }, [setData, setVisible])
  const handleTouchMove = e => {
    e?.stopPropagation?.()
  }
  const { BannerFileName, RouteType, RouteData } = data || {}
  const onClickClose = useCallback(() => {
    setVisible(false)
    const url = `${DBConfig.domainUrl}${Scenes[RouteType]}${convertParamsToString(RouteData)}`
    Taro.tracker.trackEvent(Analytic_Type.tap_pop_up_close.eventId, { url });
  }, [RouteType, RouteData])
  const openRouter = useCallback(() => {
    setVisible(false)
    const url = `${DBConfig.domainUrl}${Scenes[RouteType]}${convertParamsToString(RouteData)}`
    Taro.tracker.trackEvent(Analytic_Type.tap_pop_up.eventId, { url });
    openPage(RouteType, RouteData)
  }, [setVisible, RouteType, RouteData])
  useEffect(() => {
    if (!user) return
    const isHome = isWeb && getPathname() === Scenes.homePage
    // eslint-disable-next-line no-restricted-globals
    if (isWeb && (!isHome || isHome && location.href.indexOf(CLICK_HOME_BUTTON) > 0)) return
    fetchPopupEvent()
  }, [fetchPopupEvent, user])
  if (!visible || !data) return null
  return (
    <View className="home-pop-container" onTouchMove={handleTouchMove} style={IOS_H5_STYLE} catchMove>
      <View className="home-pop-content">
        <LoginVerifyBtn
          disabledVerify={!data?.RequestLogin}
          onClick={openRouter}
          showLogin={showLogin}
          loginSuccess={openRouter}
          className="home-pop-image-container"
        >
          <Image
            src={DBConfig.staticBannerImageUrl + BannerFileName?.[language]}
            className="home-pop-image"
          />
        </LoginVerifyBtn>
        <View className="close-btn" onClick={onClickClose}>
          <Image src={Images.home.white_close} className="home-pop-close-btn" mode="aspectFit" />
        </View>
      </View>
    </View>
  )
}
